# -*- coding:utf-8 -*-
"""
@Author : 审心
@Time : 2023/3/21 15:51
flask 服务 相关包
"""
import ctypes
import sys
import common.glv as glv
import os
import signal

from flask import Flask, request as flask_request, g as flask_glv, json
from config import data as config
from service.robot import robot_api
from common.logger.log import log_
from threading import Thread


def print_all_uri(service):
    """
    输出所有接口
    :param service: 服务对象
    :return:
    """
    log_.info("=======================已经注册的接口=========================")
    for rule in service.url_map.iter_rules():
        log_.info(rule)
    log_.info("===========================================================")


app = Flask(__name__)


# 拦截器
@app.before_request
def log_request_info():
    headers = dict(flask_request.headers)
    log_.info("\n============================flask服务接受请求===============================\n"
              + f"method : {flask_request.method}\n"
              + f"path : {flask_request.path}\n"
              + f"headers : {headers}\n"
              + f"data : {flask_request.get_data().decode('utf-8')}\n"
              + f"args : {dict(flask_request.args)}\n"
              + f"form : {dict(flask_request.form)}\n"
              + "==========================================================================")
    if headers['Content-Type'] != 'application/json;charset=UTF-8':
        raise RuntimeError("当前 flask 服务不支持该正文类型")
    # 将需要的参数存放到 flask 自带的 threading local 中 以供上下文访问
    # flask_glv.headers = headers
    data_str = flask_request.data.decode('utf-8')
    flask_glv.params = {}
    try:
        flask_glv.params = json.loads(data_str)
    except Exception as e:
        pass


@app.route('/shutdown', methods=['POST'])
def shutdown():
    """
    停止 flask 服务
    :return:
    """
    try:
        if glv.get_item("flask_pid"):
            os.kill(glv.get_item("flask_pid"), signal.SIGTERM)
        return 'Server shutting down...'
    except Exception as e:
        return f'Error shutting down server: {str(e)}'


def run(host, port):
    """
    启动flask服务
    :param host: 可见 ip 0.0.0.0 允许局域网访问
    :param port: 服务端口
    :return:
    """
    app.register_blueprint(robot_api)
    app.config['ENV'] = config.get("robot.env")
    print_all_uri(app)
    # 将当前 pid 设置为全局变量
    glv.set_item("flask_pid", os.getpid())
    app.run(host, port=port, use_reloader=False)


if __name__ == '__main__':
    thread = Thread(target=run, args=('0.0.0.0', config.get('flask.port'),))
    thread.start()
